package com.kejiguan.ui;

/**
 * Created by apple on 16/2/18.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;


import com.kejiguan.ui.util.ScreenUtils;
import com.nineoldandroids.view.ViewHelper;

import java.util.ArrayList;
import java.util.List;

public class SlidingMenu extends HorizontalScrollView {

    private GestureDetector mGestureDetector;
    private int mScreenWidth;
    private int mMenuRightPadding;
    private int mMenuWidth;
    private int mHalfMenuWidth;
    public boolean isOpen;

    private boolean once;

    private List<View> ignoredViews = new ArrayList<View>();

    private ViewGroup mMenu;
    private ViewGroup mContent;

    private boolean isLock = false;

    public SlidingMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        mGestureDetector = new GestureDetector(new HScrollDetector());
        setFadingEdgeLength(0);

    }

    public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mGestureDetector = new GestureDetector(new HScrollDetector());
        setFadingEdgeLength(0);
        mScreenWidth = ScreenUtils.getScreenWidth(context);

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.SlidingMenu, defStyle, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.SlidingMenu_rightPadding:

                    mMenuRightPadding = a.getDimensionPixelSize(attr,
                            (int) TypedValue.applyDimension(
                                    TypedValue.COMPLEX_UNIT_DIP, 50f,
                                    getResources().getDisplayMetrics()));
                    break;
            }
        }
        a.recycle();
    }

    public SlidingMenu(Context context) {
        this(context, null, 0);
        mGestureDetector = new GestureDetector(new HScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if (!once) {
            LinearLayout wrapper = (LinearLayout) getChildAt(0);
            mMenu = (ViewGroup) wrapper.getChildAt(0);
            mContent = (ViewGroup) wrapper.getChildAt(1);

            mMenuWidth = mScreenWidth - mMenuRightPadding;
            mHalfMenuWidth = mMenuWidth / 2;
            mMenu.getLayoutParams().width = mMenuWidth;
            mContent.getLayoutParams().width = mScreenWidth;

        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            Log.i(VIEW_LOG_TAG, "onLayout....");
            this.scrollTo(mMenuWidth, 0);
            once = true;
        }
    }

    public void openMenu() {
        if (isOpen)
            return;
        this.smoothScrollTo(0, 0);
        isOpen = true;
    }

    public void closeMenu() {
        if (isOpen) {
            this.smoothScrollTo(mMenuWidth, 0);
            isOpen = false;
        }
    }

    public void toggle() {

        if (!isLock) {
            if (isOpen) {
                closeMenu();
            } else {
                openMenu();
            }
        }

    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (!isLock)
        {
            Log.i(VIEW_LOG_TAG, "onScrollChanged....");
            super.onScrollChanged(l, t, oldl, oldt);
            float scale = l * 1.0f / mMenuWidth;
            float leftScale = 1 - 0.3f * scale;
            float rightScale = 0.8f + scale * 0.2f;
            ViewHelper.setTranslationX(mMenu, mMenuWidth * scale * 0.4f);
            ViewHelper.setPivotX(mContent, 0);
            ViewHelper.setPivotY(mContent, mContent.getHeight() / 2);
        }

    }

    private boolean isInIgnoredView(MotionEvent ev) {
        Rect rect = new Rect();
        for (View v : ignoredViews) {

            v.getGlobalVisibleRect(rect);

            if (rect.contains((int) ev.getX(), (int) ev.getY())) {
                if (v instanceof ViewPager) {
                    Log.d(VIEW_LOG_TAG, "v instanceof ViewPager");
                    ((ViewPager) v).requestDisallowInterceptTouchEvent(true);
                }
                return true;
            }
        }
        return false;
    }

    public void addIgnoredView(View v) {
        ignoredViews.add(v);
    }

    public void removeIgnoredView(View v) {
        ignoredViews.remove(v);
    }

    public void clearIgnoredViewList() {
        ignoredViews.clear();
    }

    private float lastActionDownX, lastActionDownY;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.d(VIEW_LOG_TAG, "onTouchEvent...");

        if (!isLock) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.d(VIEW_LOG_TAG, "MotionEvent.ACTION_DOWN...");
                    lastActionDownX = ev.getX();
                    Log.d(VIEW_LOG_TAG, "lastActionDownX..." + lastActionDownX);
                    lastActionDownY = ev.getY();
                    break;
                case MotionEvent.ACTION_MOVE:

                    break;
                case MotionEvent.ACTION_UP:
                    Log.d(VIEW_LOG_TAG, "MotionEvent.ACTION_UP...");
                    Log.d(VIEW_LOG_TAG, "getScrollX...up" + getScrollX());
                    int xOffset = (int) (ev.getX() - lastActionDownX);
                    int yOffset = (int) (ev.getY() - lastActionDownY);

                    // if (isInIgnoredView(ev)) break;
                    Log.d(VIEW_LOG_TAG, "mHalfMenuWidth===" + mHalfMenuWidth);
                    Log.d(VIEW_LOG_TAG, "xOffset===" + xOffset);
                    if (xOffset > 0) {
                        openMenu();
                    } else {
                        closeMenu();
                    }

                    return true;
                default:
                    break;
            }

            return super.onTouchEvent(ev);
        }else
        {
            return true;
        }



    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d(VIEW_LOG_TAG, "onInterceptTouchEvent...");
        if (!isLock) {
            switch (ev.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    Log.d(VIEW_LOG_TAG, "lastActionDownX...down" + ev.getX());
                    lastActionDownX = ev.getX();
                    lastActionDownY = ev.getY();

                    if (isInIgnoredView(ev))
                        return false;

                    break;

                case MotionEvent.ACTION_MOVE:
                    if (isInIgnoredView(ev))
                        return false;
                case MotionEvent.ACTION_UP:
                    if (isInIgnoredView(ev))
                        return false;
                default:
                    break;
            }

            return super.onInterceptTouchEvent(ev)
                    && mGestureDetector.onTouchEvent(ev);
        } else {
            return false;
        }


    }

    public void setLock(boolean lock) {
        isLock = lock;
    }

    class HScrollDetector extends SimpleOnGestureListener {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            if (!isLock)
            {
                Log.d(VIEW_LOG_TAG, "distanceY:distanceX ====" + distanceY + ":"
                        + distanceX);
                return Math.abs(distanceY) <= Math.abs(distanceX);
            }else
            {
                return false;
            }


        }

    }

}
